package org.swimv2.controller;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.jboss.ejb3.annotation.RemoteBinding;
import org.swimv2.model.Abilita;
import org.swimv2.model.Persona;

/**
 * Session Bean implementation class GestioneUtente
 */
@Stateless
@RemoteBinding(jndiBinding="GestioneUtenteRemote")
public class GestioneUtente implements GestioneUtenteRemote {
	@PersistenceContext(unitName="swimv2db")
	private EntityManager manager;
	
	public static final String JNDI_NAME="GestioneUtenteRemote";

    /**
     * Default constructor. 
     */
    public GestioneUtente() {
        // TODO Auto-generated constructor stub
    }

	@Override
	public void aggiungiAbilitaUtente(String tipoAbilita, String idUtente) {
		Query q1 = manager.createNamedQuery("Abilita.findByNome");
		System.out.println("Abilita:" + tipoAbilita);
		q1.setParameter("abilita", tipoAbilita);
		Abilita abilita= (Abilita)q1.getSingleResult();
		Persona persona = getUtente(idUtente);
		persona.getAbilitas().add(abilita);
		manager.persist(persona);
	}

	@Override
	public Persona getUtente(String idUtente) {	
		Query q1 = manager.createNamedQuery("Persona.findByUsername");
		q1.setParameter("username",idUtente);
		try{
		Persona persona = (Persona)q1.getSingleResult();
			return persona;
		}
		catch(NoResultException e){
			return null;
		}
		
	}

	@Override
	public List<Abilita> getAbilitaUtente(String userid) {
		Query q = manager.createNamedQuery("Abilita.findByUtente");
		q.setParameter("userId", userid);
		List<Abilita> risultato = q.getResultList();
		return risultato;
	}

}
